package com.xinhe.web.service;

import com.alibaba.fastjson.JSONObject;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.xinhe.web.common.BusinessException;
import com.xinhe.web.common.Result;
import com.xinhe.web.entity.*;
import com.xinhe.web.enums.EAssetTradeType;
import com.xinhe.web.enums.EAssetType;
import com.xinhe.web.enums.IAssetType;
import com.xinhe.web.enums.IEnumConfig;
import com.xinhe.web.reposity.*;
import com.xinhe.web.response.WithdrawalsRecordSumView;
import com.xinhe.web.response.WithdrawalsRecordView;
import com.xinhe.web.response.WithdrawalsStatisticsView;
import com.xinhe.web.util.*;
import com.xinhe.web.weixin.SendTemplateMessageModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Base64Utils;
import org.springframework.util.CollectionUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.annotation.PostConstruct;
import javax.inject.Provider;
import javax.persistence.EntityManager;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.security.PublicKey;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.xinhe.web.weixin.WXPayUtil.mapToXml;

@Slf4j
@Service
public class WithdrawalsRecordService {
    //查询工厂
    private JPAQueryFactory queryFactory;
    @Autowired
    private Provider<EntityManager> entityManager;
    @PostConstruct
    public void init() {
        queryFactory = new JPAQueryFactory(entityManager);
    }
    @Autowired
    MemberRepository memberRepository;
    @Autowired
    AssetDetailRepository assetDetailRepository;
    @Autowired
    AuthUserRepository authUserRepository;
    @Autowired
    AssetCountRepository assetCountRepository;
    @Autowired
    WithdrawalsRecordRepository withdrawalsRecordRepository;
    @Autowired
    IdentityRepository  identityRepository;
    @Autowired
    BankCardRepository bankCardRepository;
    @Autowired
    ValueConfigRepository valueConfigRepository;

    @Autowired
    AssetCountService assetCountService;
    @Autowired
    WeixinService weixinService;
    @Autowired
    WeixinConfigRepository weixinConfigRepository;
    @Autowired
    WeixinUserRepository weixinUserRepository;



    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyyMMddHHmmssSSS");


    public QueryResults<WithdrawalsRecordView> pageWithdrawalsRecord(String queryWord, Date startTime, Date endTime,
                                                                     String status,int showType,int pageNum, int pageSize) {
        QWithdrawalsRecord qWithdrawalsRecord = QWithdrawalsRecord.withdrawalsRecord;
        QMember qMember = QMember.member; ;
        QBankCard qBankCard = QBankCard.bankCard;
        BooleanBuilder builder = new BooleanBuilder();
        //builder.and(qWithdrawalsRecord.removed.eq(0));
        if (StringUtils.isNotEmpty(queryWord)) {
            builder.and(qMember.name.contains(queryWord).or(qMember.mobile.contains(queryWord)));
        }
        if (!Objects.isNull(status)) {
            builder.and(qWithdrawalsRecord.status.contains(status));
        }
        //查询昨天一天的记录
        if (!Objects.isNull(showType) && showType == 0) {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, -1);
            Date yesterday = calendar.getTime();
            builder.and(qWithdrawalsRecord.createTime.after(yesterday));
            //查询今天的
        }else if (!Objects.isNull(showType) && showType == 1) {
            // 设置今天的0点
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            Date startOfDay = calendar.getTime();
            // 设置今天的23:59:59秒
            calendar.set(Calendar.HOUR_OF_DAY, 23);
            calendar.set(Calendar.MINUTE, 59);
            calendar.set(Calendar.SECOND, 59);
            calendar.set(Calendar.MILLISECOND, 999);
            Date endOfDay = calendar.getTime();
            builder.and(qWithdrawalsRecord.createTime.between(startOfDay,endOfDay));
        }
        return queryFactory.select(
                        Projections.bean(
                                WithdrawalsRecordView.class,
                                qWithdrawalsRecord.id,
                                qWithdrawalsRecord.fUserId.as("userId"),
                                qWithdrawalsRecord.money,
                                qWithdrawalsRecord.serviceFee,
                                qWithdrawalsRecord.realityAccountFee,
                                qWithdrawalsRecord.status,
                                qWithdrawalsRecord.type,
                                qWithdrawalsRecord.assetType,
                                qWithdrawalsRecord.mode,
                                qWithdrawalsRecord.checkRemark,
                                qWithdrawalsRecord.code,
                                qWithdrawalsRecord.isMember,
                                qWithdrawalsRecord.wxPayMoney,
                                qWithdrawalsRecord.accountTime,
                                //qWithdrawalsRecord.createTime,
                                qMember.code,
                                qMember.parentCode,
                                qMember.gender,
                                qMember.level,
                                qMember.role,
                                qMember.roleTwo,
                                qMember.adoptionDate,
                                qMember.adoptionNum,
                                qMember.newReference,
                                qMember.identifying,
                                qMember.twoThawNo,
                                qMember.threeThawNo,
                                qMember.twoThawAdopted,
                                qMember.threeThawAdopted,
                                qMember.isImportMember,
                                qMember.disengageNo,
                                qMember.name,
                                qMember.mobile,
                                qBankCard.bankName,
                                qBankCard.name.as("bankUserName"),
                                qBankCard.code.as("bankCode")
                        )
                ).from(qWithdrawalsRecord)
                .leftJoin(qMember).on(qWithdrawalsRecord.fUserId.eq(qMember.fUserId).and(qMember.removed.eq(0)))
                .leftJoin(qBankCard).on(qWithdrawalsRecord.fUserId.eq(qBankCard.id))
                .where(builder).offset(pageNum * pageSize).limit(pageSize).fetchResults();
    }
    public QueryResults<WithdrawalsRecordView> pageUserWithdrawalsRecord(Long userId, int pageNum, int pageSize) {
        QWithdrawalsRecord qWithdrawalsRecord = QWithdrawalsRecord.withdrawalsRecord;
        QMember qMember = QMember.member; ;
        QBankCard qBankCard = QBankCard.bankCard;
        BooleanBuilder builder = new BooleanBuilder();
        //builder.and(qWithdrawalsRecord.removed.eq(0));
        if (!Objects.isNull(userId)) {
            builder.and(qWithdrawalsRecord.fUserId.eq(userId));
        }
        return queryFactory.select(
                        Projections.bean(
                                WithdrawalsRecordView.class,
                                qWithdrawalsRecord.id,
                                qWithdrawalsRecord.fUserId.as("userId"),
                                qWithdrawalsRecord.money,
                                qWithdrawalsRecord.serviceFee,
                                qWithdrawalsRecord.realityAccountFee,
                                qWithdrawalsRecord.status,
                                qWithdrawalsRecord.type,
                                qWithdrawalsRecord.assetType,
                                qWithdrawalsRecord.mode,
                                qWithdrawalsRecord.checkRemark,
                                qWithdrawalsRecord.code,
                                qWithdrawalsRecord.isMember,
                                qWithdrawalsRecord.wxPayMoney,
                                qWithdrawalsRecord.accountTime,
                                //qWithdrawalsRecord.createTime,
                                qMember.code,
                                qMember.parentCode,
                                qMember.gender,
                                qMember.level,
                                qMember.role,
                                qMember.roleTwo,
                                qMember.adoptionDate,
                                qMember.adoptionNum,
                                qMember.newReference,
                                qMember.identifying,
                                qMember.twoThawNo,
                                qMember.threeThawNo,
                                qMember.twoThawAdopted,
                                qMember.threeThawAdopted,
                                qMember.isImportMember,
                                qMember.disengageNo,
                                qMember.name,
                                qMember.mobile,
                                qBankCard.bankName,
                                qBankCard.name.as("bankUserName"),
                                qBankCard.code.as("bankCode")
                        )
                ).from(qWithdrawalsRecord)
                .leftJoin(qMember).on(qWithdrawalsRecord.fUserId.eq(qMember.fUserId).and(qMember.removed.eq(0)))
                .leftJoin(qBankCard).on(qWithdrawalsRecord.fUserId.eq(qBankCard.id))
                .where(builder).offset(pageNum * pageSize).limit(pageSize).fetchResults();
    }

    public Result<WithdrawalsRecordSumView> findByWithdrawalsRecordSumAmount() {
        WithdrawalsRecordSumView recordSumView = new WithdrawalsRecordSumView();
        QWithdrawalsRecord qWithdrawalsRecord = QWithdrawalsRecord.withdrawalsRecord;
        QMember qMember = QMember.member; ;
        QBankCard qBankCard = QBankCard.bankCard;
        List<WithdrawalsRecordView> withdrawalsRecordViews = queryFactory.select(
                        Projections.bean(
                                WithdrawalsRecordView.class,
                                qWithdrawalsRecord.id,
                                qWithdrawalsRecord.fUserId.as("userId"),
                                qWithdrawalsRecord.money,
                                qWithdrawalsRecord.serviceFee,
                                qWithdrawalsRecord.realityAccountFee,
                                qWithdrawalsRecord.status,
                                qWithdrawalsRecord.type,
                                qWithdrawalsRecord.assetType,
                                qWithdrawalsRecord.mode,
                                qWithdrawalsRecord.checkRemark,
                                qWithdrawalsRecord.code,
                                qWithdrawalsRecord.isMember,
                                qWithdrawalsRecord.wxPayMoney,
                                qWithdrawalsRecord.accountTime,
                                //qWithdrawalsRecord.createTime,
                                qMember.code,
                                qMember.parentCode,
                                qMember.gender,
                                qMember.level,
                                qMember.role,
                                qMember.roleTwo,
                                qMember.adoptionDate,
                                qMember.adoptionNum,
                                qMember.newReference,
                                qMember.identifying,
                                qMember.twoThawNo,
                                qMember.threeThawNo,
                                qMember.twoThawAdopted,
                                qMember.threeThawAdopted,
                                qMember.isImportMember,
                                qMember.disengageNo,
                                qMember.name,
                                qMember.mobile,
                                qBankCard.bankName,
                                qBankCard.name.as("bankUserName"),
                                qBankCard.code.as("bankCode")
                        )
                ).from(qWithdrawalsRecord)
                .leftJoin(qMember).on(qWithdrawalsRecord.fUserId.eq(qMember.fUserId).and(qMember.removed.eq(0)))
                .leftJoin(qBankCard).on(qWithdrawalsRecord.fUserId.eq(qBankCard.id))
                .fetch();
        if (!CollectionUtils.isEmpty(withdrawalsRecordViews)) {
            BigDecimal money = withdrawalsRecordViews.stream().map(WithdrawalsRecordView::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal serviceFee = withdrawalsRecordViews.stream().map(WithdrawalsRecordView::getServiceFee).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal realityAccountFee = withdrawalsRecordViews.stream().map(WithdrawalsRecordView::getRealityAccountFee).reduce(BigDecimal.ZERO, BigDecimal::add);
            recordSumView.setMoney(money);
            recordSumView.setServiceFee(serviceFee);
            recordSumView.setRealityAccountFee(realityAccountFee);
        }
        return Result.ok(recordSumView);
    }
    public Result<WithdrawalsStatisticsView> findByWithdrawalsStatistics() {
        Integer yestDayCount = withdrawalsRecordRepository.findBySumCountYest();
        BigDecimal yestDayMoney = withdrawalsRecordRepository.findBySumMoneyYest();
        BigDecimal yestDayServiceFee = withdrawalsRecordRepository.findBySumServiceFeeYest();
        BigDecimal yestDayRealityAccountFee = withdrawalsRecordRepository.findBySumRealityAccountFeeYest();

        Integer toDayCount = withdrawalsRecordRepository.findBySumCountToday();
        BigDecimal toDayMoney = withdrawalsRecordRepository.findBySumMoneyToday();
        BigDecimal toDayServiceFee = withdrawalsRecordRepository.findBySumServiceFeeToday();
        BigDecimal toDayRealityAccountFee = withdrawalsRecordRepository.findBySumRealityAccountFeeToday();
        WithdrawalsStatisticsView w = new WithdrawalsStatisticsView();
        w.setYestDayCount(yestDayCount);
        w.setYestDayMoney(yestDayMoney);
        w.setYestDayServiceFee( yestDayServiceFee);
        w.setYestDayRealityAccountFee(yestDayRealityAccountFee);
        w.setToDayCount(toDayCount);
        w.setToDayMoney(toDayMoney);
        w.setToDayServiceFee(toDayServiceFee);
        w.setToDayRealityAccountFee(toDayRealityAccountFee);
        return Result.ok(w);
    }

    protected String generateGoodsOrderCode() {
        StringBuilder code = new StringBuilder();
        code.append(simpleDateFormat2.format(new Date()));
        Double codeRandom = Double.valueOf(Math.random() * 10000.0D);
        code.append(codeRandom.intValue());
        return code.toString();
    }

    @Transactional
    public void autoWithdrawalsBank() {
        System.out.println("进来自动提现了");
        List<Member> members = this.memberRepository.findAll();
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(members)) {
            for (Member member : members) {
                if ("FREEZE".equals(member.getMemberStatus())) {
                    continue;
                }
                Identity identity = this.identityRepository.findByUserId(member.getFUserId());
                if (identity == null || !identity.getCheckStatus().equals("SUCCESS")) {
                    continue;
                }
                AssetCount assetCount = this.assetCountService.findByTypeAndUserId("RMB", member.getFUserId()).getData();
                if (null != assetCount && assetCount.getRemainder().compareTo(new BigDecimal(110)) >= 0) {
                    BankCard bankCard = this.bankCardRepository.findOneByUserIdAndIsDefault(member.getFUserId(), Integer.valueOf(1));
                    if (null != bankCard) {
                        BigDecimal balance = assetCount.getRemainder().subtract(new BigDecimal(10));
                        //提现到银行卡服务费率% 6
                        BigDecimal rate = new BigDecimal(valueConfigRepository.findById("withdrawals_service_rate_bank").get().getValue());
                        BigDecimal money = balance.subtract(balance.remainder(new BigDecimal(100)));
                        BigDecimal serviceFee = money.multiply(new BigDecimal("0.01")).multiply(rate).setScale(2, 1);
                        if (balance.compareTo(new BigDecimal(100)) >= 0 && (new BigDecimal(20000)).compareTo(money.subtract(serviceFee)) > 0) {
                            log.info("进来小于2W提现了,提现金额为:{}", money);
                            WithdrawalsRecord withdrawalsRecord = new WithdrawalsRecord();
                            withdrawalsRecord.setAssetType("RMB");
                            withdrawalsRecord.setfUserId(member.getFUserId());
                            withdrawalsRecord.setMoney(money);
                            withdrawalsRecord.setType("BALANCE");
                            withdrawalsRecord.setServiceFee(serviceFee);
                            withdrawalsRecord.setRealityAccountFee(withdrawalsRecord.getMoney().subtract(serviceFee));
                            withdrawalsRecord.setCode(generateGoodsOrderCode());
                            withdrawalsRecord.setfBankId(bankCard.getId());
                            withdrawalsRecord.setIsMember(Integer.valueOf(1));
                            withdrawalsRecord.setMode("PAY_TO_BANK_CARD");
                            BigDecimal payMoney = withdrawalsRecord.getRealityAccountFee().multiply(new BigDecimal("0.001")).setScale(2, 3);
                            System.out.println("手续费为:" + payMoney);
                            if (payMoney.compareTo(new BigDecimal(1)) >= 0 && payMoney.compareTo(new BigDecimal(25)) <= 0) {
                                withdrawalsRecord.setWxPayMoney(withdrawalsRecord.getRealityAccountFee().add(payMoney));
                            } else {
                                withdrawalsRecord.setWxPayMoney(withdrawalsRecord.getRealityAccountFee().add(new BigDecimal(1)));
                            }
                            Integer count = this.withdrawalsRecordRepository.findByUserIdAndDays(member.getFUserId());
                            if (count.intValue() > 0) {
                                withdrawalsRecord.setStatus("APPLY");
                            }
                            else if (withdrawalsRecord.getMoney().compareTo(new BigDecimal(500)) >= 0) {
                                withdrawalsRecord.setStatus("APPLY");
                            } else {
                                withdrawalsRecord.setStatus("IN_TRANSFER_ACCOUNTS");
                            }
                            this.withdrawalsRecordRepository.save(withdrawalsRecord);
                            Result assetResult = this.assetCountService.saveRemainderAsset(withdrawalsRecord
                                    .getfUserId(), "RMB","SYSTEM_WITHDRAWAL", withdrawalsRecord
                                    .getMoney().negate(), withdrawalsRecord.getId(),"",new Date());

                            if (withdrawalsRecord.getStatus().equals("IN_TRANSFER_ACCOUNTS")) {
                                System.out.println("进来定时自动转账了");
                                transferAccounts(new HashSet<>(Collections.singletonList(withdrawalsRecord.getId())));
                                continue;
                            }
                            List<Long> list = new ArrayList<>();
                            list.add(Long.valueOf(549840853032501248L));
                            list.add(Long.valueOf(576985188559486976L));
                            try {
                                Map<String, String> data = new HashMap<>();
                                data.put("thing1", member.getName());
                                data.put("amount3", withdrawalsRecord.getMoney().toString());
                                for (int i = 0; i < 2; i++) {
                                    this.weixinService.sendTemplateMessage(SendTemplateMessageModel.builder()
                                            .userId(list.get(i))
                                            .pagePath("")
                                            .templateId("5TDKQoD3GxGNPS-eY3zZ88M2O-Nf3zNIyXLk4EDyYD0")
                                            .data(data)
                                            .build());
                                }
                            } catch (Exception e) {
                                log.info("提现异常:{}", e.getMessage());
                            }  continue;
                        }
                        if (balance.compareTo(new BigDecimal(100)) >= 0 && balance.compareTo(new BigDecimal(20010)) > 0) {
                            log.info("进来余额大于2W提现了,提现金额为:{}", balance);
                            BigDecimal fee = new BigDecimal("20000");
                            BigDecimal serviceMoney = fee.multiply(new BigDecimal("0.01")).multiply(rate).setScale(2, 1);
                            WithdrawalsRecord withdrawalsRecord = new WithdrawalsRecord();
                            withdrawalsRecord.setAssetType("RMB");
                            withdrawalsRecord.setfUserId(member.getFUserId());
                            withdrawalsRecord.setMoney(fee);
                            withdrawalsRecord.setType("BALANCE");
                            withdrawalsRecord.setServiceFee(serviceMoney);
                            withdrawalsRecord.setRealityAccountFee(withdrawalsRecord.getMoney().subtract(serviceMoney));
                            withdrawalsRecord.setCode(generateGoodsOrderCode());
                            withdrawalsRecord.setfBankId(bankCard.getId());
                            withdrawalsRecord.setIsMember(Integer.valueOf(1));
                            withdrawalsRecord.setMode("PAY_TO_BANK_CARD");
                            BigDecimal payMoney = withdrawalsRecord.getRealityAccountFee().multiply(new BigDecimal("0.001")).setScale(2, 3);
                            System.out.println("手续费为:" + payMoney);
                            if (payMoney.compareTo(new BigDecimal(1)) >= 0 && payMoney.compareTo(new BigDecimal(25)) <= 0) {
                                withdrawalsRecord.setWxPayMoney(withdrawalsRecord.getRealityAccountFee().add(payMoney));
                            } else {
                                withdrawalsRecord.setWxPayMoney(withdrawalsRecord.getRealityAccountFee().add(new BigDecimal(1)));
                            }
                            Integer count = this.withdrawalsRecordRepository.findByUserIdAndDays(member.getFUserId());
                            if (count.intValue() > 0) {
                                withdrawalsRecord.setStatus("APPLY");
                            }
                            else if (withdrawalsRecord.getMoney().compareTo(new BigDecimal(500)) >= 0) {
                                withdrawalsRecord.setStatus("APPLY");
                            } else {
                                withdrawalsRecord.setStatus("IN_TRANSFER_ACCOUNTS");
                            }
                            this.withdrawalsRecordRepository.save(withdrawalsRecord);
                            Result assetResult = this.assetCountService.saveRemainderAsset(withdrawalsRecord
                                    .getfUserId(), "RMB", "SYSTEM_WITHDRAWAL", withdrawalsRecord
                                    .getMoney().negate(), withdrawalsRecord.getId(),"",new Date());

                            if (withdrawalsRecord.getStatus().equals("IN_TRANSFER_ACCOUNTS")) {
                                System.out.println("进来定时自动转账了");
                                transferAccounts(new HashSet<>(Collections.singletonList(withdrawalsRecord.getId())));
                                continue;
                            }
                            List<Long> list = new ArrayList<>();
                            list.add(Long.valueOf(549840853032501248L));
                            list.add(Long.valueOf(576985188559486976L));
                            try {
                                Map<String, String> data = new HashMap<>();
                                data.put("thing1", member.getName());
                                data.put("amount3", withdrawalsRecord.getMoney().toString());
                                for (int i = 0; i < 2; i++) {
                                    this.weixinService.sendTemplateMessage(SendTemplateMessageModel.builder()
                                            .userId(list.get(i))
                                            .pagePath("")
                                            .templateId("5TDKQoD3GxGNPS-eY3zZ88M2O-Nf3zNIyXLk4EDyYD0")
                                            .data(data)
                                            .build());
                                }
                            } catch (Exception e) {
                                log.info("提现异常:{}", e.getMessage());
                            }
                        }
                    }
                }
            }
        }
    }

    private Result transferAccounts(Set<Long> transferAccountsIds) {
        System.out.println("进来提现结果了转账了");
        List<WithdrawalsRecord> withdrawalsRecords = this.withdrawalsRecordRepository.findByIdIn(transferAccountsIds);
        for (WithdrawalsRecord withdrawalsRecord : withdrawalsRecords) {
            if ("WEIXIN_TRANSFER_ACCOUNTS".equals(withdrawalsRecord.getMode())) {
                String transferBat = weixinTransferBat(withdrawalsRecord.getId());
                JSONObject jsonObject = JSONObject.parseObject(transferBat);
                System.out.println("提现结果:" + jsonObject);
                String code = jsonObject.getString("code");
                if (StringUtils.isNotBlank(code)) {
                    return Result.failed(3300,jsonObject.getString("message"));
                }
                continue;
            }
            try {
                Result baseResult = transferBank(withdrawalsRecord.getId());
                if (0 != baseResult.getCode()) {
                    System.out.println("111111");
                    //withdrawalsRecord.setCheckRemark(e.getMessage());
                    return Result.failed(3301,baseResult.getMessage());
                }
            } catch (BusinessException e) {
                System.out.println("22222");
                log.error("错误信息:" + e.getMessage());
                return Result.failed(3302,e.getMessage());
            } catch (Exception e) {
                System.out.println("33333");
                e.printStackTrace();
                log.error("错误信息:" + e.getMessage());
                withdrawalsRecord.setCheckRemark(e.getMessage());
                return Result.failed(3303,e.getMessage());
            }
        }
        return Result.ok();
    }

    public String weixinTransferBat(Long id) {
        WithdrawalsRecord withdrawalsRecord = this.withdrawalsRecordRepository.findById(id).get();
        //小程序微信配置ID 519802482830868480
        Long weixin_config_id_mini_program = Long.valueOf(this.valueConfigRepository.findById("weixin_config_id_mini_program").get().getValue());
        WeixinConfig weixinConfig = this.weixinConfigRepository.findById(weixin_config_id_mini_program).get();
        WeixinUser weixinUser = this.weixinUserRepository.findOneByConfigIdAndUserId(weixin_config_id_mini_program, withdrawalsRecord.getfUserId());
        String openId = weixinUser.getOpenid();
        Map<String, Object> postMap = new HashMap<>();
        String outNo = CharCodeUtil.generateCharRandomCode(32);
        postMap.put("appid", weixinConfig.getAppId());
        postMap.put("out_batch_no", withdrawalsRecord.getCode());
        postMap.put("batch_name", "转账");
        postMap.put("batch_remark", "转账");
        postMap.put("total_amount", Integer.valueOf(withdrawalsRecord.getMoney().multiply(BigDecimal.valueOf(100L)).setScale(1, 4).intValue()));
        postMap.put("total_num", Integer.valueOf(1));
        List<Map> list = new ArrayList<>();
        Map<String, Object> subMap = new HashMap<>(4);
        subMap.put("out_detail_no", withdrawalsRecord.getId().toString());
        subMap.put("transfer_amount", withdrawalsRecord.getMoney().multiply(new BigDecimal(100)));
        subMap.put("transfer_remark", "明细备注");
        subMap.put("openid", openId);
        list.add(subMap);
        postMap.put("transfer_detail_list", list);
        String resStr = HttpUtil.postTransBatRequest("https://api.mch.weixin.qq.com/v3/transfer/batches",
                JSONObject.toJSONString(postMap), "57906AE4C493222D0DDD03D81A3A2F2AA93B8D19",
                weixinConfig.getMchId(), "/root/apiclient_key.pem");
        return resStr;
    }
    public Result transferBank(Long id) throws Exception {
        QWithdrawalsRecord qWithdrawalsRecord =QWithdrawalsRecord.withdrawalsRecord;
        QMember qMember = QMember.member; ;
        QBankCard qBankCard = QBankCard.bankCard;
        BooleanBuilder builder = new BooleanBuilder();
        if (!Objects.isNull(id)) {
            builder.and(qWithdrawalsRecord.id.eq(id));
        }
        WithdrawalsRecordView view = queryFactory.select(
                        Projections.bean(
                                WithdrawalsRecordView.class,
                                qWithdrawalsRecord.id,
                                qWithdrawalsRecord.fUserId,
                                qWithdrawalsRecord.money,
                                qWithdrawalsRecord.serviceFee,
                                qWithdrawalsRecord.realityAccountFee,
                                qWithdrawalsRecord.status,
                                qWithdrawalsRecord.type,
                                qWithdrawalsRecord.assetType,
                                qWithdrawalsRecord.mode,
                                qWithdrawalsRecord.checkRemark,
                                qWithdrawalsRecord.code,
                                qWithdrawalsRecord.isMember,
                                qWithdrawalsRecord.wxPayMoney,
                                qWithdrawalsRecord.accountTime,
                                qWithdrawalsRecord.createTime,
                                qMember.name,
                                qMember.parentCode,
                                qMember.gender,
                                qMember.level,
                                qMember.role,
                                qMember.roleTwo,
                                qMember.adoptionDate,
                                qMember.adoptionNum,
                                qMember.newReference,
                                qMember.identifying,
                                qMember.twoThawNo,
                                qMember.threeThawNo,
                                qMember.twoThawAdopted,
                                qMember.threeThawAdopted,
                                qMember.isImportMember,
                                qMember.disengageNo,
                                qMember.name,
                                qMember.mobile,
                                qBankCard.bankType,
                                qBankCard.bankName,
                                qBankCard.name.as("bankUserName"),
                                qBankCard.code.as("bankCode")
                        )
                ).from(qWithdrawalsRecord)
                .leftJoin(qMember).on(qWithdrawalsRecord.fUserId.eq(qMember.fUserId).and(qMember.removed.eq(0)))
                .leftJoin(qBankCard).on(qWithdrawalsRecord.fUserId.eq(qBankCard.id))
                .where(builder).fetchOne();
        Integer payMoney = Integer.valueOf(view.getRealityAccountFee().multiply(BigDecimal.valueOf(100L)).setScale(1, 4).intValue());
        Map<String, String> data = new HashMap<>();
        System.out.println("户名:" + view.getBankUserName());
        data.put("mch_id", PropertyTool.getValue("/wxpay.properties", "MCHId"));
        data.put("partner_trade_no", view.getId().toString());
        data.put("nonce_str", view.getCode());
        data.put("enc_bank_no", encrypt(view.getBankCode()));
        data.put("enc_true_name", encrypt(view.getBankUserName()));
        data.put("bank_code", view.getBankType());
        data.put("amount", payMoney.toString());
        data.put("desc", "转账");
        String sign = createTransferBankSign(data);
        data.put("sign", sign);
        String xml = mapToXml(data);
        System.out.println("请求xml：" + xml);
        String mchId = PropertyTool.getValue("wxpay.properties", "MCHId");
        String certFilePath = PropertyTool.getValue("wxpay.properties", "certs.path");
        String response = PayUtil.doPublicKey(mchId, PropertyTool.getValue("wxpay.properties", "TRANSFERSBANKURL"), xml, certFilePath);
        System.out.println("回调xml：" + response);
        Map<String, String> map = xmlToMap(response);
        System.out.println("转map：" + map);
        String returnCode = map.get("return_code");
        if (!"SUCCESS".equals(returnCode)) {
            System.out.println("444444");
            log.error(map.get("return_msg"));
            return Result.failed(444444,map.get("return_msg"));
        }
        String resultCode = map.get("result_code");
        if (!"SUCCESS".equals(resultCode)) {
            System.out.println("55555");
            log.error("错误信息", map.get("err_code_des"));
            return Result.failed(55555,map.get("err_code_des"));
        }
        return Result.ok();
    }

    public static String encrypt(String data) {
        PublicKey pub = null;
        try {
            pub = RSAUtils.getPublicKey("RSA");
            String rsa = "RSA/ECB/OAEPWITHSHA-1ANDMGF1PADDING";
            byte[] estrName = RSAUtils.encrypt(data.getBytes(), pub, 2048, 11, rsa);

            data = Base64Utils.encodeToString(estrName);
            return data;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String createTransferBankSign(Map<String, String> bean) {
        StringBuffer sign = new StringBuffer();
        sign.append("amount=").append(bean.get("amount"));
        sign.append("&bank_code=").append(bean.get("bank_code"));
        if (StringUtils.isNotBlank(bean.get("desc"))) {
            sign.append("&desc=").append(bean.get("desc"));
        }
        sign.append("&enc_bank_no=").append(bean.get("enc_bank_no"));
        sign.append("&enc_true_name=").append(bean.get("enc_true_name"));
        sign.append("&mch_id=").append(bean.get("mch_id"));
        sign.append("&nonce_str=").append(bean.get("nonce_str"));
        sign.append("&partner_trade_no=").append(bean.get("partner_trade_no"));
        sign.append("&key=").append(PropertyTool.getValue("wxpay.properties", "APIKEY"));
        System.out.println("付款到银行卡签名参数：" + sign.toString());
        String signStr = Md5Util.getInstance().getLongToken(sign.toString()).toUpperCase();
        System.out.println("付款到银行卡签名：" + signStr);
        return signStr;
    }

    public static Map<String, String> xmlToMap(String strXML) {
        Map<String, String> data = new HashMap<>();
        try {
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
            Document doc = documentBuilder.parse(stream);
            doc.getDocumentElement().normalize();
            NodeList nodeList = doc.getDocumentElement().getChildNodes();
            for (int idx = 0; idx < nodeList.getLength(); idx++) {
                Node node = nodeList.item(idx);
                if (node.getNodeType() == 1) {
                    Element element = (Element)node;
                    data.put(element.getNodeName(), element.getTextContent());
                }
            }
            try {
                stream.close();
            } catch (Exception ex) {}

        }
        catch (Exception e) {
            throw new RuntimeException("微信参数错误");
        }
        return data;
    }
    @Transactional
    public void autoSelectBank() {
        List<WithdrawalsRecord> withdrawalsRecords = this.withdrawalsRecordRepository.findByAllAndType();
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(withdrawalsRecords)) {
            for (WithdrawalsRecord withdrawalsRecord : withdrawalsRecords) {

                String url = String.format("https://api.mch.weixin.qq.com/mmpaysptrans/query_bank", new Object[0]);
                Map<String, String> data = new HashMap<>();
                String str = UUID.randomUUID().toString().replaceAll("-", "");
                data.put("mch_id", PropertyTool.getValue("wxpay.properties", "MCHId"));
                data.put("partner_trade_no", withdrawalsRecord.getId().toString());
                data.put("nonce_str", str);
                String sign = createPostPublicKeySign(data);
                data.put("sign", sign);
                try {
                    String xml = mapToXml(data);
                    System.out.println("请求xml：" + xml);
                    String mchId = PropertyTool.getValue("wxpay.properties", "MCHId");
                    String certFilePath = PropertyTool.getValue("wxpay.properties", "certs.path");
                    String response = PayUtil.doPublicKey(mchId, url, xml, certFilePath);
                    System.out.println(response);
                    Map<String, String> map = xmlToMap(response);
                    String returnCode = map.get("return_code");
                    if ("SUCCESS".equals(returnCode)) {
                        String resultCode = map.get("result_code");
                        if ("SUCCESS".equals(resultCode)) {
                            String status = map.get("status");
                            if ("SUCCESS".equals(status)) {
                                withdrawalsRecord.setStatus("TRANSFER_ACCOUNTS_SUCCESS");
                                withdrawalsRecord.setAccountTime(new Date());
                                this.withdrawalsRecordRepository.saveAndFlush(withdrawalsRecord);
                                continue;
                            } if ("FAILED".equals(status)) {
                                String err_code = map.get("reason");
                                Result assetResult = this.assetCountService.saveRemainderAsset(withdrawalsRecord
                                        .getfUserId(),withdrawalsRecord.getAssetType(),"USER_WITHDRAWAL_REJECT", withdrawalsRecord
                                        .getMoney(), withdrawalsRecord.getId(),"",new Date());
                                if (0 != assetResult.getCode()) {
                                    throw new BusinessException(3001,assetResult.getMessage());
                                }
                                withdrawalsRecord.setStatus("TRANSFER_ACCOUNTS_REJECT");
                                withdrawalsRecord.setCheckRemark(err_code);
                                this.withdrawalsRecordRepository.saveAndFlush(withdrawalsRecord);
                                Member member = this.memberRepository.findByUserId(withdrawalsRecord.getfUserId());
                                try {
                                    Map<String, String> datas = new HashMap<>();
                                    datas.put("thing1", member.getName());
                                    datas.put("time3", (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(withdrawalsRecord.getCreateTime()));
                                    this.weixinService.sendTemplateMessage(SendTemplateMessageModel.builder()
                                            .userId(Long.valueOf(549840853032501248L))
                                            .pagePath("")
                                            .templateId("soSwXlBNIIqmnZkXIx0Uuy-PaTwTt6adOM0mL9LNtmk")
                                            .data(datas)
                                            .build());
                                } catch (Exception e) {
                                    System.out.println(e.getMessage());
                                }
                            }  continue;
                        }  if (resultCode.equals("FAIL")) {
                            System.out.println("订单不存在");
                            String return_msg = map.get("return_msg");
                            Result assetResult = this.assetCountService.saveRemainderAsset(withdrawalsRecord
                                    .getfUserId(),withdrawalsRecord.getAssetType(),"USER_WITHDRAWAL_REJECT", withdrawalsRecord
                                    .getMoney(), withdrawalsRecord.getId(),"",new Date());
                            if (0 != assetResult.getCode()) {
                                throw new BusinessException(3001,assetResult.getMessage());
                            }
                            withdrawalsRecord.setStatus("TRANSFER_ACCOUNTS_REJECT");
                            //withdrawalsRecord.setRemark(return_msg);
                            this.withdrawalsRecordRepository.saveAndFlush(withdrawalsRecord);
                            Member member = this.memberRepository.findByUserId(withdrawalsRecord.getfUserId());
                            try {
                                Map<String, String> datas = new HashMap<>();
                                datas.put("thing1", member.getName());
                                datas.put("time3", (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(withdrawalsRecord.getCreateTime()));
                                this.weixinService.sendTemplateMessage(SendTemplateMessageModel.builder()
                                        .userId(Long.valueOf(549840853032501248L))
                                        .pagePath("")
                                        .templateId("soSwXlBNIIqmnZkXIx0Uuy-PaTwTt6adOM0mL9LNtmk")
                                        .data(datas)
                                        .build());
                            } catch (Exception e) {
                                System.out.println(e.getMessage());
                            }

                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static String createPostPublicKeySign(Map<String, String> map) {
        StringBuffer sign = new StringBuffer();
        sign.append("mch_id=").append(map.get("mch_id"));
        sign.append("&nonce_str=").append(map.get("nonce_str"));
        sign.append("&partner_trade_no=").append(map.get("partner_trade_no"));
        sign.append("&key=").append(PropertyTool.getValue("wxpay.properties", "APIKEY"));
        String signStr = Md5Util.getInstance().getLongToken(sign.toString()).toUpperCase();
        System.out.println("获取公钥签名：" + signStr);
        return signStr;
    }
    //@ANoRepeatRequest
    @Transactional(rollbackFor = {Exception.class})
    public Result saveWithdrawalsRecord(Long userId,BigDecimal money,String type,String remark,Long bankId,String mode) {
        Member member = this.memberRepository.findByUserId(userId);
        if ("FREEZE".equals(member.getMemberStatus())) {
            return Result.failed(101,"账号已被冻结!");
        }
        if (!money.remainder(new BigDecimal("100")).equals(BigDecimal.ZERO)) {
            return Result.failed(101,"提现金额必须是100的整数倍");
        }
        Identity identity = this.identityRepository.findByUserId(userId);
        if (identity == null || !identity.getCheckStatus().equals("SUCCESS")) {
            return Result.failed(101,"未实名认证，请先进行实名认证");
        }
        AssetCount assetCount = this.assetCountService.findByTypeAndUserId(EAssetType.RMB.getName(), userId).getData();
        if (money.compareTo(assetCount.getRemainder()) > 0) {
            return Result.failed(101,"提现金额不能大于可提现金额");
        }
        if (assetCount.getRemainder().subtract(money).compareTo(new BigDecimal(10)) < 0) {
            return Result.failed(101,"账户余额不能低于10元");
        }
        BigDecimal rate = BigDecimal.ZERO;
        if ("WEIXIN_TRANSFER_ACCOUNTS".equals(mode)) {
            //配置的提现服务费率%6
            rate = new BigDecimal(6);
        } else {
            //配置的提现到银行卡服务费率%6
            rate = new BigDecimal(6);
        }
        BigDecimal serviceFee = (new BigDecimal(money.toString())).multiply(new BigDecimal("0.01")).multiply(rate).setScale(2, 1);
        BigDecimal toDayMoney = this.withdrawalsRecordRepository.findByUserIdAndSumToDayMoney(userId);
        if ((new BigDecimal("20000")).compareTo(toDayMoney.add(money.subtract(serviceFee))) <= 0) {
            return Result.failed(101,"单日提现金额上限为20000,实际提现到账金额为：" + toDayMoney);
        }
        String assetType = "BALANCE".equals(type)? "RMB" : "";
        WithdrawalsRecord withdrawalsRecord = new WithdrawalsRecord();
        withdrawalsRecord.setAssetType(assetType);
        withdrawalsRecord.setfUserId(userId);
        withdrawalsRecord.setMoney(money);
        withdrawalsRecord.setType(type);
        withdrawalsRecord.setServiceFee(serviceFee);
        withdrawalsRecord.setRealityAccountFee(withdrawalsRecord.getMoney().subtract(serviceFee));
        withdrawalsRecord.setCode(generateGoodsOrderCode());
        withdrawalsRecord.setfBankId(bankId);
        withdrawalsRecord.setIsMember(Integer.valueOf(0));
        withdrawalsRecord.setMode(mode);
        BigDecimal payMoney = withdrawalsRecord.getRealityAccountFee().multiply(new BigDecimal("0.001")).setScale(2, 3);
        if (payMoney.compareTo(new BigDecimal(1)) >= 0 && payMoney.compareTo(new BigDecimal(25)) <= 0) {
            withdrawalsRecord.setWxPayMoney(withdrawalsRecord.getRealityAccountFee().add(payMoney));
        } else {
            withdrawalsRecord.setWxPayMoney(withdrawalsRecord.getRealityAccountFee().add(new BigDecimal(1)));
        }
        Integer count = this.withdrawalsRecordRepository.findByUserIdAndDays(member.getFUserId());
        if (count.intValue() > 0) {
            withdrawalsRecord.setStatus("APPLY");
        }
        else if (money.compareTo(new BigDecimal(500)) >= 0) {
            withdrawalsRecord.setStatus("APPLY");
        } else {
            withdrawalsRecord.setStatus("IN_TRANSFER_ACCOUNTS");
        }
        this.withdrawalsRecordRepository.save(withdrawalsRecord);
        Result<AssetDetail> assetResult = this.assetCountService.saveRemainderAsset(withdrawalsRecord
                .getfUserId(), assetType, "USER_WITHDRAWAL", withdrawalsRecord
                .getMoney().negate(), withdrawalsRecord.getId(),"",new Date());
        if (0!=assetResult.getCode()) {
            return Result.failed(101,assetResult.getMessage());
        }
        if (!"WEIXIN_TRANSFER_ACCOUNTS".equals(mode)) {
            if (withdrawalsRecord.getStatus().equals("IN_TRANSFER_ACCOUNTS")) {
                transferAccounts(new HashSet<>(Collections.singletonList(withdrawalsRecord.getId())));
            } else {
                try {
                    List<Long> list = new ArrayList<>();
                    list.add(Long.valueOf(549840853032501248L));
                    list.add(Long.valueOf(576985188559486976L));
                    Map<String, String> data = new HashMap<>();
                    data.put("thing1", member.getName());
                    data.put("amount3", withdrawalsRecord.getMoney().toString());
                    for (int i = 0; i < 2; i++) {
                        this.weixinService.sendTemplateMessage(SendTemplateMessageModel.builder()
                                .userId(list.get(i))
                                .pagePath("")
                                .templateId("5TDKQoD3GxGNPS-eY3zZ88M2O-Nf3zNIyXLk4EDyYD0")
                                .data(data)
                                .build());
                    }
                } catch (Exception e) {
                    log.info("提现异常:{}", e.getMessage());
                }
            }
        }
        return Result.ok();
    }
    //@ANoRepeatRequest
    @Transactional(rollbackFor = {Exception.class})
    public Result saveCheck(Set<Long> ids,String checkResult,String remark) {
        List<WithdrawalsRecord> withdrawalsRecords = this.withdrawalsRecordRepository.findByIdIn(ids);
        Set<Long> transferAccountsIds = new HashSet<>();
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(withdrawalsRecords)) {
            for (WithdrawalsRecord wr : withdrawalsRecords) {
                if ("APPLY" == wr.getStatus()) {
                    if ("FAILURE".equals(checkResult)) {
                        Result<AssetDetail> assetResult = this.assetCountService.saveRemainderAsset(wr
                                .getfUserId(), wr.getAssetType(),"USER_WITHDRAWAL_REJECT", wr
                                .getMoney(), wr.getId(),"",new Date());
                        if (0!=assetResult.getCode()) {
                            return Result.failed(101,assetResult.getMessage());
                        }
                        wr.setStatus("REJECT");
                        wr.setCheckRemark(remark);
                        this.withdrawalsRecordRepository.saveAndFlush(wr);
                        continue;
                    }if ("SUCCESS".equals(checkResult)) {
                        wr.setStatus("IN_TRANSFER_ACCOUNTS");
                        this.withdrawalsRecordRepository.saveAndFlush(wr);
                        transferAccountsIds.add(wr.getId());
                    }
                }
            }
        } else {
            return Result.failed(102,"未选择数据");
        }
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(transferAccountsIds)) {
            transferAccounts(transferAccountsIds);
        }
        return Result.ok();
    }
    public Result<WithdrawalsRecordView> detailWithdrawalsRecord(Long withdrawalsRecordId) {
        QWithdrawalsRecord qWithdrawalsRecord =QWithdrawalsRecord.withdrawalsRecord;
        QMember qMember = QMember.member; ;
        QBankCard qBankCard = QBankCard.bankCard;
        BooleanBuilder builder = new BooleanBuilder();
        if (!Objects.isNull(withdrawalsRecordId)) {
            builder.and(qWithdrawalsRecord.id.eq(withdrawalsRecordId));
        }
        WithdrawalsRecordView withdrawalsRecordView = queryFactory.select(
                        Projections.bean(
                                WithdrawalsRecordView.class,
                                qWithdrawalsRecord.id,
                                qWithdrawalsRecord.fUserId,
                                qWithdrawalsRecord.money,
                                qWithdrawalsRecord.serviceFee,
                                qWithdrawalsRecord.realityAccountFee,
                                qWithdrawalsRecord.status,
                                qWithdrawalsRecord.type,
                                qWithdrawalsRecord.assetType,
                                qWithdrawalsRecord.mode,
                                qWithdrawalsRecord.checkRemark,
                                qWithdrawalsRecord.code,
                                qWithdrawalsRecord.isMember,
                                qWithdrawalsRecord.wxPayMoney,
                                qWithdrawalsRecord.accountTime,
                                qWithdrawalsRecord.createTime,
                                qMember.name,
                                qMember.parentCode,
                                qMember.gender,
                                qMember.level,
                                qMember.role,
                                qMember.roleTwo,
                                qMember.adoptionDate,
                                qMember.adoptionNum,
                                qMember.newReference,
                                qMember.identifying,
                                qMember.twoThawNo,
                                qMember.threeThawNo,
                                qMember.twoThawAdopted,
                                qMember.threeThawAdopted,
                                qMember.isImportMember,
                                qMember.disengageNo,
                                qMember.name,
                                qMember.mobile,
                                qBankCard.bankType,
                                qBankCard.bankName,
                                qBankCard.name.as("bankUserName"),
                                qBankCard.code.as("bankCode")
                        )
                ).from(qWithdrawalsRecord)
                .leftJoin(qMember).on(qWithdrawalsRecord.fUserId.eq(qMember.fUserId).and(qMember.removed.eq(0)))
                .leftJoin(qBankCard).on(qWithdrawalsRecord.fUserId.eq(qBankCard.id))
                .where(builder).fetchOne();

        return Result.ok(withdrawalsRecordView);
    }
    public Result<BigDecimal> findByMemberWithdrawalsMoney(Long userId) {
        BigDecimal money = this.withdrawalsRecordRepository.findByUserIdAndStatus(userId,"TRANSFER_ACCOUNTS_SUCCESS");
        return Result.ok(money);
    }

   /*
    public static final String PRIVATE_KEY_PATH = "/root/apiclient_key.pem";


    private static final String WECHAT_PAY_SERIAL_NO = "57906AE4C493222D0DDD03D81A3A2F2AA93B8D19";


    private static final String CHARSET = "UTF-8";


    @Autowired
    private IWeixinService weixinService;

    public BeanResult<String> easyWithdrawalsRecordExcel(WithdrawalsRecordQuery query) {
        query.setLimit(Integer.valueOf(-1));
        BeanResult<String> result = new BeanResult();

        List<WithdrawalsRecordView> withdrawalsRecordViews = this.withdrawalsRecordDao.pageWithdrawalsRecord(query);
        if (CollectionUtils.isEmpty(withdrawalsRecordViews)) {
            throw new BusinessException("你没有可以导出的数据");
        }
        List<WithdrawalsRecordEasyView> easyViews = new ArrayList<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        for (WithdrawalsRecordView view : withdrawalsRecordViews) {
            WithdrawalsRecordEasyView easyView = new WithdrawalsRecordEasyView();
            easyView.setCreateTime(format.format(view.getCreateTime()));
            easyView.setName(view.getName());
            easyView.setMobile(view.getMobile());
            easyView.setMoney(view.getMoney());
            easyView.setServiceFee(view.getServiceFee());
            easyView.setRealityAccountFee(view.getRealityAccountFee());
            easyView.setBankName(view.getBankName());
            easyView.setBankCode(view.getBankCode());
            easyView.setBankUserName(view.getBankUserName());
            easyView.setStatus(EWithdrawStatus.valueOf(view.getStatus()).getLabel());
            easyView.setIsMember((0 == view.getIsMember().intValue()) ? "会员提现" : "系统提现");
            easyViews.add(easyView);
        }

        String name = "会员提现记录";

        File file = createFile(name);

        System.out.println("导出的值为：" + easyViews);

        if (CollectionUtils.isNotEmpty(easyViews)) {
            ((ExcelWriterSheetBuilder)EasyExcel.write(file).sheet("提现记录")
                    .head(WithdrawalsRecordEasyView.class))
                    .doWrite(easyViews);
            result.setItem("/temp/" + file.getName());
            System.out.println("导出的路径名称为:" + file.getName());
        }
        System.out.println("导出的路径名称为:" + file.getName());
        return result;
    }

    private static File createFile(String name) {
        String filePath = "/usr/local/webapps/xhyp/resources/temp";
        File fileDir = new File(filePath);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

        File file = new File(filePath, String.format("%s%s_%s.xlsx", new Object[] { name, simpleDateFormat.format(new Date()), Integer.valueOf((int)(Math.random() * 100000.0D)) }));
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return file;
    }
    public static void main(String[] args) {
        BigDecimal balance = (new BigDecimal(999)).subtract(new BigDecimal(10));


        BigDecimal money = balance.subtract(balance.remainder(new BigDecimal(100)));
        BigDecimal serviceFee = money.multiply(new BigDecimal("0.01")).multiply(new BigDecimal(6)).setScale(2, 1);
        BigDecimal fee = money.subtract(serviceFee);
        if (balance.compareTo(new BigDecimal(100)) >= 0 && (new BigDecimal(20000)).compareTo(money.subtract(serviceFee)) > 0) {
            System.out.println("进来这里了");
        } else {
            System.out.println(1111);
        }
    }


    @Transactional
    public void autoSelect() {
        List<WithdrawalsRecord> withdrawalsRecords = this.withdrawalsRecordDao.findByAll();
        if (CollectionUtils.isNotEmpty(withdrawalsRecords))
        {
            for (WithdrawalsRecord withdrawalsRecord : withdrawalsRecords) {

                JSONObject jsonObject = this.httpUtil.searchTransBatRequest(withdrawalsRecord.getCode(), withdrawalsRecord.getId().toString());
                if (jsonObject != null) {
                    String detailStatus = jsonObject.getString("detail_status");
                    System.out.println("状态为：" + detailStatus);
                    if ("SUCCESS".equals(detailStatus)) {
                        withdrawalsRecord.setStatus(EWithdrawStatus.TRANSFER_ACCOUNTS_SUCCESS);
                        this.withdrawalsRecordDao.update((BaseEntityImpl)withdrawalsRecord); continue;
                    }  if ("FAIL".equals(detailStatus)) {
                        withdrawalsRecord.setStatus(EWithdrawStatus.TRANSFER_ACCOUNTS_REJECT);
                        this.withdrawalsRecordDao.update((BaseEntityImpl)withdrawalsRecord);
                        BeanResult<AssetDetail> assetResult = this.assetCountService.saveRemainderAsset(new AssetTradeModel(withdrawalsRecord
                                .getUserId(), (IAssetType)withdrawalsRecord.getAssetType(), (IEnumConfig)EAssetTradeType.USER_WITHDRAWAL_REJECT, withdrawalsRecord
                                .getMoney(), withdrawalsRecord.getId()));
                        if (!assetResult.getSuccess().booleanValue()) {
                            throw new BusinessException(assetResult);
                        }
                    }
                }
            }
        }
    }

    public static String createGetPublicKeySign(Map<String, String> map) {
        StringBuffer sign = new StringBuffer();
        sign.append("mch_id=").append(map.get("mch_id"));
        sign.append("&nonce_str=").append(map.get("nonce_str"));
        sign.append("&sign_type=").append(map.get("sign_type"));
        sign.append("&key=").append(PropertyTool.getValue("wxpay.properties", "APIKEY"));
        System.out.println("获取公钥签名参数：" + sign.toString());
        String signStr = Md5Util.getInstance().getLongToken(sign.toString()).toUpperCase();
        System.out.println("获取公钥签名：" + signStr);
        return signStr;
    }

    public static Map<String, String> getPublicKey() throws Exception {
        Map<String, String> data = new HashMap<>();
        String str = UUID.randomUUID().toString();
        data.put("mch_id", PropertyTool.getValue("wxpay.properties", "MCHId"));
        data.put("nonce_str", str);
        data.put("sign_type", "MD5");

        String sign = createGetPublicKeySign(data);
        data.put("sign", sign);

        String xml = mapToXml(data);
        System.out.println("请求xml：" + xml);

        String mchId = PropertyTool.getValue("wxpay.properties", "MCHId");
        String certFilePath = PropertyTool.getValue("wxpay.properties", "certs.path");

        String response = PayUtil.doPublicKey(mchId, PropertyTool.getValue("wxpay.properties", "GETPUBLICKEY"), xml, certFilePath);
        System.out.println(response);
        Map<String, String> map = xmlToMap(response);
        return map;
    }

    public static String mapToXml(Map<String, String> data) throws Exception {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.newDocument();
        Element root = document.createElement("xml");
        document.appendChild(root);
        for (String key : data.keySet()) {
            String value = data.get(key);
            if (value == null) {
                value = "";
            }
            value = value.trim();
            Element filed = document.createElement(key);
            filed.appendChild(document.createTextNode(value));
            root.appendChild(filed);
        }
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        DOMSource source = new DOMSource(document);
        transformer.setOutputProperty("encoding", "utf-8");
        transformer.setOutputProperty("indent", "yes");
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        transformer.transform(source, result);
        String output = writer.getBuffer().toString();
        try {
            writer.close();
        } catch (Exception ex) {}

        return output;
    }



   */
}
